package topcbl.room;

import java.util.Vector;

public class Room {
	Vector<Player> teamTrai;
	Vector<Player> teamPhai;
	private int mMaxPlayers;

	public Room(int maxOfPlayers) {
		mMaxPlayers = maxOfPlayers;
		teamTrai = new Vector<Player>();
		teamPhai = new Vector<Player>();
	}

	public void addPlayer(Player player) {
		if (teamTrai.size() <= teamPhai.size()) {
			teamTrai.add(player);
			player.setTeam(Team.TRAI);
		} else {
			teamPhai.add(player);
			player.setTeam(Team.PHAI);
		}
	}

	public void removePlayer(Player player) {
		switch (player.getTeam()) {
		case TRAI:
			teamTrai.remove(player);
			break;
		case PHAI:
			teamPhai.remove(player);
			break;
		}
	}

	public void changeTeam(Player player) {
		switch (player.getTeam()) {
		case TRAI:
			teamTrai.remove(player);
			teamPhai.add(player);
			player.setTeam(Team.PHAI);
			break;
		case PHAI:
			teamPhai.remove(player);
			teamTrai.add(player);
			player.setTeam(Team.TRAI);
			break;
		}
	}

	public boolean isFull() {
		if (teamTrai.size() + teamPhai.size() < mMaxPlayers)
			return false;
		else
			return true;
	}

	public boolean canPlay() {
		if (teamTrai.size() == teamPhai.size())
			return true;
		else
			return false;
	}

	public Player getLeftPlayer(int pos) {
		return teamTrai.get(pos);
	}

	public Player getRightPlayer(int pos) {
		return teamPhai.get(pos);
	}

	public int getMaxOfPlayer() {
		return mMaxPlayers;
	}

	public int getNumberOfPlayer() {
		return teamTrai.size() + teamPhai.size();
	}

	public void send2AllPlayer(String data) {
		for (int i = 0; i < teamTrai.size(); i++) {
			teamTrai.get(i).sendMessage(data);
		}
		for (int i = 0; i < teamPhai.size(); i++) {
			teamPhai.get(i).sendMessage(data);
		}
	}

	public void send2AllPlayerWithout1(String data, Player exceptivePlayer) {
		for (int i = 0; i < teamTrai.size(); i++) {
			if (teamTrai.get(i) != exceptivePlayer)
				teamTrai.get(i).sendMessage(data);
		}
		for (int i = 0; i < teamPhai.size(); i++) {
			if (teamPhai.get(i) != exceptivePlayer)
				teamPhai.get(i).sendMessage(data);
		}
	}

	public void closeAllSocket() {
		for (int i = 0; i < teamTrai.size(); i++) {
			teamTrai.get(i).closeConnect();
		}
		for (int i = 0; i < teamPhai.size(); i++) {
			teamPhai.get(i).closeConnect();
		}
	}
	
	public void refresh(){
		for (int i = 0; i < teamTrai.size(); i++) {
			teamTrai.get(i).sendMessage("REFRESH_0");
		}
		for (int i = 0; i < teamPhai.size(); i++) {
			teamPhai.get(i).sendMessage("REFRESH_0");
		}
	}
}
